<!-- src/components/ExportUrlDrawer.vue -->
<template>
    <el-drawer :model-value="modelValue" title="导出URL列表" direction="rtl" size="600px"
        @close="$emit('update:modelValue', false)" @closed="$emit('closed')">
        <div class.drawer-content="drawer-content">
            <el-form :model="form" label-width="120px" ref="formRef" class="drawer-form">
                <el-form-item label="文件名是否编码">
                    <div class="form-item-content">
                        <el-switch v-model="form.encode_filename" active-text="是" inactive-text="否" inline-prompt />
                        <el-tooltip class="box-item" effect="dark"
                            content="开启后，CSV中的文件名将保持URL编码格式（如 %E4%B8%AD%E6%96%87.txt）；关闭后，将显示为可读的UTF-8格式（如 中文.txt）。"
                            placement="top">
                            <el-icon style="margin-left: 8px; cursor: pointer;">
                                <QuestionFilled />
                            </el-icon>
                        </el-tooltip>
                    </div>
                </el-form-item>
                <el-form-item label="过期时间">
                    <el-input-number v-model="form.expires_in" :min="1" :max="604800" controls-position="right" />
                    <span style="margin-left: 8px;">秒</span>
                </el-form-item>
            </el-form>
        </div>

        <template #footer>
            <div style="text-align: left;">
                <el-button type="primary" @click="handleSubmit" :loading="isSubmitting">
                    {{ isSubmitting ? '正在导出...' : '确 定' }}
                </el-button>
                <el-button @click="handleClose">取消</el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script setup>
import { ref, watch } from 'vue';
import apiClient from '@/api';
import { ElMessage, ElNotification } from 'element-plus';
import { QuestionFilled } from '@element-plus/icons-vue';
import { saveAs } from 'file-saver'; // 我们需要这个库来处理文件下载

const props = defineProps({
    modelValue: Boolean,
    bucketName: { type: String, required: true },
    selectedItems: { type: Array, default: () => [] },
});

const emit = defineEmits(['update:modelValue', 'closed']);

const isSubmitting = ref(false);
const form = ref({
    encode_filename: true,
    expires_in: 300,
});

const handleSubmit = async () => {
    if (props.selectedItems.length === 0) {
        ElMessage.warning('没有选中的文件');
        return;
    }
    isSubmitting.value = true;
    try {
        const payload = {
            items: props.selectedItems.map(item => ({ name: item.name })),
            expires_in: form.value.expires_in,
            encode_filename: form.value.encode_filename,
        };

        const response = await apiClient.post(
            `/api/v1/buckets/${props.bucketName}/export-urls`,
            payload,
            {
                responseType: 'blob', // 告诉 Axios 我们期望接收一个二进制文件
            }
        );

        // 从响应头中提取文件名
        let filename = `exported_urls_${props.bucketName}.csv`;
        const contentDisposition = response.headers['content-disposition'];
        if (contentDisposition) {
            const filenameMatch = contentDisposition.match(/filename="(.+)"/);
            if (filenameMatch && filenameMatch.length > 1) {
                filename = filenameMatch[1];
            }
        }

        // 使用 file-saver 库来触发下载
        saveAs(new Blob([response.data]), filename);

        ElNotification({
            title: '导出成功',
            message: `已成功导出 ${props.selectedItems.length} 个文件的URL。`,
            type: 'success',
        });

        emit('update:modelValue', false);
    } catch (error) {
        console.error("导出URL失败:", error);
        ElMessage.error(error.response?.data?.error || '导出URL失败，请重试');
    } finally {
        isSubmitting.value = false;
    }
};

const handleClose = () => {
    emit('update:visible', false);
};
</script>

<style scoped>
.drawer-content {
    display: flex;
    flex-direction: column;
    height: 100%;
}

.drawer-form {
    flex-grow: 1;
    overflow-y: auto;
}

.form-item-content {
    display: flex;
    align-items: center;
}

.drawer-footer {
    flex-shrink: 0;
    padding-top: 20px;
    border-top: 1px solid var(--el-border-color);
    display: flex;
    justify-content: flex-end;
}
</style>